package cn.itcast.hotel.listen;

import cn.itcast.hotel.client.HotelAdminClient;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HotelQueueListen {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private HotelAdminClient hotelAdminClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("hotel.insert.queue"),
            exchange = @Exchange(value = "hotel.topic",type = ExchangeTypes.TOPIC),
            key = "hotel.insert"
    ))
    public void listenInsertQueue(Long hotelId){
        try {
            Hotel hotel = hotelAdminClient.queryById(hotelId);
            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
            System.err.println("接收到修改id"+hotelId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("hotel.delete.queue"),
            exchange = @Exchange(value = "hotel.topic",type = ExchangeTypes.TOPIC),
            key = "hotel.delete"
    ))
    public void listenDeleteQueue(Long hotelId){
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", hotelId.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
            System.err.println("删除id成功"+hotelId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

